//
//  MXAddUserViewController.m
//  HNBaseProject
//
//  Created by AAA on 2024/6/5.
//

#import "MXAddUserViewController.h"
#import "MXAddUserCell.h"
#import "DCAlterView.h"
#import "MXSearchUserModel.h"
@interface MXAddUserViewController () <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UITextField *searchTextField;

@property (nonatomic, strong) NSMutableArray *userArray;
@end

@implementation MXAddUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /// 测试数据请删除
//    self.searchTextField.text = @"黄晓明";
    self.userArray = [[NSMutableArray alloc] init];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MXAddUserCell" bundle:nil] forCellReuseIdentifier:@"MXAddUserCell"];
}

- (IBAction)backButtonClick:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)searchTextFieldEditing:(id)sender {
    
//    [self.tableView reloadData];
}

- (IBAction)searchButtonClick:(id)sender {
    
    [self.view endEditing:YES];
    [self getUserWithText:self.searchTextField.text];
}

- (void)getUserWithText:(NSString *)text {
    if (text.length == 0) {
        [self.view xjmakeToast:@"请输入昵称或手机号"];
        return;
    }
    //全是数字
    NSDictionary *param = @{@"selectValue":SAFEPARAMETER(text)};
     
    MJWeakSelf
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:@"api/app/appUser/selectUserInfoByPhoneOrNickName" params:param httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            [weakSelf.userArray removeAllObjects];
            NSArray *dataArray =  [NSArray modelArrayWithClass:[MXSearchUserModel class] json:dict[@"data"]];
            [weakSelf.userArray addObjectsFromArray:dataArray];
            [weakSelf.tableView reloadData];
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (BOOL)deptNumInputShouldNumber:(NSString *)str
{
   if (str.length == 0) {
        return NO;
    }
    NSString *regex = @"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if ([pred evaluateWithObject:str]) {
        return YES;
    }
    return NO;
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.userArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MXSearchUserModel *model = self.userArray[indexPath.row];
    MXAddUserCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MXAddUserCell" forIndexPath:indexPath];
    cell.nameLab.text = model.username;
    cell.inviteButton.userInteractionEnabled = NO;
    cell.phoneLab.text = [NSString stringWithFormat:@"手机号:%@",model.phoneNumber];
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MXSearchUserModel *model = self.userArray[indexPath.row];
    DCAlterView * alterView = [[DCAlterView alloc] initWithTitle:@"" content:@"已发送共享通知，对方接受共享后，就可以使用家庭中的设备、查看家庭宠物的信息哦~"];
    MJWeakSelf
    [alterView addActionWithTitle:@"我知道了" color:[UIColor colorWithHexString:@"#3378F8"] type:DCAlterTypeDone halderBlock:^(UIButton *button) {
        [weakSelf inviteUserWithModel:model];
    }];
    
    [DC_KeyWindow addSubview:alterView];
}

- (void)inviteUserWithModel:(MXSearchUserModel *)model {

    MJWeakSelf
    NSDictionary *param = @{@"inviteFamilyId" : SAFEPARAMETER(self.inviteFamilyId),
                            @"invitedUserId"  : model.ID};
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:@"api/app/family/inviteUserIntoFamily" params:param httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            [weakSelf.view xjmakeToast:@"邀请成功"];
            [weakSelf performSelector:@selector(backNav) afterDelay:1.5];
        } else {
            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)backNav {
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITableViewDelegate


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self dc_navBarHidden:YES];
}

@end
